package com.zisu.rabbitproducer.component;

import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;

import java.io.IOException;
import java.util.List;

/**
 * @Desc: ""
 * @Author: caixiang
 * @DATE: 2021/4/26 14:46
 */
// JSON/对象转换类
public class JsonUtils {
    // 定义jackson对象
    private static ObjectMapper MAPPER=new ObjectMapper();

    // 将对象转换成json字符串
    public static String objectToJson(Object obj){
        try {
            String str=MAPPER.writeValueAsString(obj);
            return str;
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        return null;
    }

    // 将json数据转换成pojo对象
    public static <T> T jsonToObject(String json,Class<T> beanType){
        try {
            T t=MAPPER.readValue(json, beanType);
            return t;
        } catch (JsonParseException e) {
            e.printStackTrace();
        } catch (JsonMappingException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    // 将json数据转换成pojo对象list
    public static <T> List<T> jsonToList(String json, Class<T> beanType){
        JavaType javaType=MAPPER.getTypeFactory().constructParametricType(List.class, beanType);
        try{
            List<T> list=MAPPER.readValue(json, javaType);
            return list;
        }catch(Exception e){
            e.printStackTrace();
        }
        return null;
    }
}
